/**
 * @Description:  微信小程序模块
 * @author longfa liang
 * @date 2021/7/15
 */

const request = require("request")
const config = require("../config/config")
const fs = require("fs")
var COS = require('cos-nodejs-sdk-v5');

var qiniu = require("qiniu")


var accessKey = config.qiniu.accessKey;
var secretKey = config.qiniu.secretKey;
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

var cos = new COS({
    getAuthorization: function (options, callback) {

        // TODO 这里根据自己业务需要做好放行判断
        if (!allowScope()) {
            console.log('deny Scope');
            return;
        }

        // 获取临时密钥
        var policy = STS.getPolicy(options.Scope);
        STS.getCredential({
            secretId: config.SecretId,
            secretKey: config.SecretKey,
            policy: policy,
            // durationSeconds: 1800,
            proxy: '',
            region: 'ap-guangzhou'
        }, function (err, data) {
            if (err) {
                console.error(err);
            } else {
                console.log(data);
                var credentials = data.credentials;
                callback({
                    TmpSecretId: credentials.tmpSecretId,
                    TmpSecretKey: credentials.tmpSecretKey,
                    SecurityToken: credentials.sessionToken,
                    ExpiredTime: data.expiredTime,
                    ScopeLimit: true, // 设为 true 可限制密钥只在相同请求可重用，默认不限制一直可重用，细粒度控制权限需要设为 true
                });
            }
        });

    },
});

class WxResult {

    getOpenId(code) {
        var url = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.wx.appid}&secret=${config.wx.appsecret}&js_code=${code}&grant_type=authorization_code`;
        return new Promise((r, e) => {
            request(url, (err, res, body) => {
                if (body.errcode) {
                    r(false)
                } else {
                    try {
                        r(JSON.parse(body))
                    } catch (e) {
                        console.error(e)
                        r(false)
                    }
                }
            })
        })
    }

    getauthKey() {

        var options = {
            scope: "niushifserver",
            expires: 600
        };
        var putPolicy = new qiniu.rs.PutPolicy(options);
        var uploadToken = putPolicy.uploadToken(mac);

        return uploadToken
    }

    uploadCos(path, filename, Prefix) {
        return new Promise((r, e) => {
            cos.putObject({
                Bucket: config.cos.bucket, /* 必须 */
                Region: config.cos.region, /* 必须 */
                Key: filename, /* 必须 */
                Prefix: Prefix || "",
                Body: fs.createReadStream(path), // 上传文件对象
                onProgress: function (progressData) {
                    console.log(JSON.stringify(progressData));
                }
            }, function (err, data) {
                if (err) {
                    console.error(err)
                    r(false)
                } else {
                    console.log("上传成功", path, "https://" + data.Location)
                    r("https://" + data.Location)
                }
            });
        })
    }


}

module.exports = new WxResult()